﻿using System.Linq;
using System.Web.Mvc;
using OneDollarStore.Models;

namespace OneDollarStore.Controllers
{
    public class ShoppingCartController : Controller
    {
        StoreModelEntities storeDB = new StoreModelEntities();
        
        public ViewResult Index()
        {
            // Get ShoppingCard
            var cart = ShoppingCartModel.GetCart(this.HttpContext);
            var shoppingCartViewModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };
            return View(shoppingCartViewModel);
        }

        // id: ProductID
        public RedirectToRouteResult AddToCart(int id)
        {
            var addedProduct = storeDB.SerialProducts.FirstOrDefault(d => d.SerialProductID == id);
            //storeDB.Detach(addedProduct);
            var cart = ShoppingCartModel.GetCart(this.HttpContext);
            cart.AddToCart(addedProduct);
            return RedirectToAction("Index");
        }

        [HttpPost]
        // id: RecordID
        public ActionResult RemoveFromCart(int id)
        {
            var cart = ShoppingCartModel.GetCart(this.HttpContext);
            var product = storeDB.Carts.Include("SerialProduct").FirstOrDefault(c => c.RecordID == id);
            string productName = "";
            if (product != null)
            {
                productName = product.SerialProduct.Name;
            }
            else
            {
                return RedirectToAction("Index");
            }
            cart.RemoveFromCart(id);
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(productName) + 
                    " has been removed from your cart.",
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                DeletedID = id
            };
            return Json(results);
        }

        [ChildActionOnly]
        public ActionResult CartSummary()
        {
            var cart = ShoppingCartModel.GetCart(this.HttpContext);
            ViewData["CartCount"] = cart.GetCount();
            return PartialView("CartSummary");
        }
    }
}